{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .transaction-filters {
        background: white;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .transaction-list {
        background: white;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .transaction-item {
        border-bottom: 1px solid #f0f0f0;
        padding: 1.5rem;
        transition: all 0.3s ease;
        position: relative;
    }

    .transaction-item:last-child {
        border-bottom: none;
    }

    .transaction-item:hover {
        background: #f8f9fa;
        transform: translateX(5px);
    }

    .transaction-type-badge {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        border-radius: 0 2px 2px 0;
    }

    .type-recharge {
        background: #28a745;
    }

    .type-consume {
        background: #dc3545;
    }

    .type-refund {
        background: #17a2b8;
    }

    .transaction-amount {
        font-size: 1.2rem;
        font-weight: bold;
    }

    .amount-positive {
        color: #28a745;
    }

    .amount-negative {
        color: #dc3545;
    }

    .amount-neutral {
        color: #6c757d;
    }

    .transaction-status {
        padding: 0.25rem 0.75rem;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .status-completed {
        background: #d4edda;
        color: #155724;
    }

    .status-pending {
        background: #fff3cd;
        color: #856404;
    }

    .status-failed {
        background: #f8d7da;
        color: #721c24;
    }

    .transaction-meta {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-top: 0.5rem;
    }

    .meta-item {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        font-size: 0.9rem;
        color: #6c757d;
    }

    .filter-form .form-control,
    .filter-form .form-select {
        border-radius: 8px;
        border: 1px solid #dee2e6;
    }

    .filter-form .form-control:focus,
    .filter-form .form-select:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
    }

    .pagination-wrapper {
        background: white;
        border-radius: 10px;
        padding: 1rem;
        margin-top: 1rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .pagination {
        margin: 0;
        justify-content: center;
    }

    .pagination .page-item .page-link {
        border-radius: 6px;
        margin: 0 2px;
        border: 1px solid #dee2e6;
    }

    .pagination .page-item.active .page-link {
        background: #007bff;
        border-color: #007bff;
    }

    .empty-state {
        text-align: center;
        padding: 3rem 2rem;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    .transaction-summary {
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
        color: white;
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }

    .summary-item {
        text-align: center;
    }

    .summary-value {
        font-size: 1.5rem;
        font-weight: bold;
        display: block;
    }

    .summary-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }

    @media (max-width: 768px) {
        .transaction-meta {
            flex-direction: column;
            align-items: flex-start;
        }

        .transaction-item {
            padding: 1rem;
        }

        .summary-item {
            margin-bottom: 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="page-title">
                <i class="fas fa-list-alt me-2"></i>交易记录
            </h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ url_for('dashboard.student') }}">首页</a></li>
                    <li class="breadcrumb-item"><a href="{{ url_for('accounts.balance') }}">账户余额</a></li>
                    <li class="breadcrumb-item active">交易记录</li>
                </ol>
            </nav>
        </div>
    </div>

    <!-- 交易概览 -->
    {% if pagination.total > 0 %}
    <div class="transaction-summary">
        <div class="row">
            <div class="col-md-3">
                <div class="summary-item">
                    <span class="summary-value">{{ pagination.total }}</span>
                    <small class="summary-label">总交易数</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="summary-item">
                    <span class="summary-value" id="totalIncome">¥0.00</span>
                    <small class="summary-label">总收入</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="summary-item">
                    <span class="summary-value" id="totalExpense">¥0.00</span>
                    <small class="summary-label">总支出</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="summary-item">
                    <span class="summary-value" id="netAmount">¥0.00</span>
                    <small class="summary-label">净额</small>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- 筛选器 -->
    <div class="transaction-filters">
        <form method="GET" class="filter-form" id="filterForm">
            <div class="row g-3">
                <div class="col-md-3">
                    {{ form.transaction_type.label(class="form-label") }}
                    {{ form.transaction_type(class="form-select") }}
                </div>
                <div class="col-md-2">
                    {{ form.start_date.label(class="form-label") }}
                    {{ form.start_date(class="form-control") }}
                </div>
                <div class="col-md-2">
                    {{ form.end_date.label(class="form-label") }}
                    {{ form.end_date(class="form-control") }}
                </div>
                <div class="col-md-2">
                    {{ form.page_size.label(class="form-label") }}
                    {{ form.page_size(class="form-select") }}
                </div>
                <div class="col-md-3">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-2"></i>筛选
                        </button>
                        <a href="{{ url_for('accounts.transactions') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-redo me-2"></i>重置
                        </a>
                        <button type="button" class="btn btn-outline-success" id="exportBtn">
                            <i class="fas fa-download me-2"></i>导出
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 交易列表 -->
    <div class="transaction-list">
        {% if transactions %}
            {% for transaction in transactions %}
            <div class="transaction-item">
                <!-- 交易类型标识 -->
                <div class="transaction-type-badge type-{{ transaction.type }}"></div>

                <div class="row align-items-center">
                    <div class="col-lg-6">
                        <div class="d-flex align-items-start">
                            <div class="me-3">
                                <!-- 交易类型图标 -->
                                {% if transaction.type == 'recharge' %}
                                    <i class="fas fa-plus-circle fa-2x text-success"></i>
                                {% elif transaction.type == 'consume' %}
                                    <i class="fas fa-minus-circle fa-2x text-danger"></i>
                                {% elif transaction.type == 'refund' %}
                                    <i class="fas fa-undo fa-2x text-info"></i>
                                {% else %}
                                    <i class="fas fa-exchange-alt fa-2x text-muted"></i>
                                {% endif %}
                            </div>
                            <div class="flex-grow-1">
                                <h6 class="mb-1">{{ transaction.description }}</h6>
                                <div class="transaction-meta">
                                    <div class="meta-item">
                                        <i class="fas fa-clock"></i>
                                        {{ transaction.created_at.strftime('%Y-%m-%d %H:%M:%S') }}
                                    </div>
                                    {% if transaction.payment_method %}
                                    <div class="meta-item">
                                        <i class="fas fa-credit-card"></i>
                                        {% if transaction.payment_method == 'alipay' %}支付宝
                                        {% elif transaction.payment_method == 'wechat' %}微信支付
                                        {% elif transaction.payment_method == 'offline' %}线下支付
                                        {% else %}{{ transaction.payment_method }}
                                        {% endif %}
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-3 text-lg-center">
                        <span class="transaction-status status-completed">
                            <i class="fas fa-check-circle me-1"></i>已完成
                        </span>
                    </div>

                    <div class="col-lg-3 text-lg-end">
                        <div class="transaction-amount
                            {% if transaction.amount > 0 %}amount-positive
                            {% elif transaction.amount < 0 %}amount-negative
                            {% else %}amount-neutral
                            {% endif %}">
                            {% if transaction.amount > 0 %}+{% endif %}¥{{ "%.2f"|format(transaction.amount) }}
                        </div>
                        <div class="mt-1">
                            <a href="{{ url_for('accounts.transaction_detail', transaction_id=transaction.id) }}"
                               class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-eye me-1"></i>详情
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="empty-state">
                <i class="fas fa-receipt"></i>
                <h5>暂无交易记录</h5>
                <p class="text-muted">您还没有任何交易记录</p>
                <a href="{{ url_for('accounts.recharge') }}" class="btn btn-primary">
                    <i class="fas fa-plus-circle me-2"></i>立即充值
                </a>
            </div>
        {% endif %}
    </div>

    <!-- 分页 -->
    {% if pagination.pages > 1 %}
    <div class="pagination-wrapper">
        <nav aria-label="交易记录分页">
            <ul class="pagination">
                <!-- 首页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_prev }}">
                    <a class="page-link" href="{{ url_for('accounts.transactions', page=1, **request.args) }}"
                       aria-label="首页">
                        <i class="fas fa-angle-double-left"></i>
                    </a>
                </li>

                <!-- 上一页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_prev }}">
                    <a class="page-link" href="{{ url_for('accounts.transactions', page=pagination.current_page-1, **request.args) }}"
                       aria-label="上一页">
                        <i class="fas fa-angle-left"></i>
                    </a>
                </li>

                <!-- 页码 -->
                {% set start_page = pagination.current_page - 2 if pagination.current_page > 2 else 1 %}
                {% set end_page = pagination.current_page + 2 if pagination.current_page + 2 < pagination.pages else pagination.pages %}

                {% if start_page > 1 %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('accounts.transactions', page=1, **request.args) }}">1</a>
                    </li>
                    {% if start_page > 2 %}
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    {% endif %}
                {% endif %}

                {% for page_num in range(start_page, end_page + 1) %}
                    <li class="page-item {{ 'active' if page_num == pagination.current_page }}">
                        <a class="page-link" href="{{ url_for('accounts.transactions', page=page_num, **request.args) }}">
                            {{ page_num }}
                        </a>
                    </li>
                {% endfor %}

                {% if end_page < pagination.pages %}
                    {% if end_page < pagination.pages - 1 %}
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    {% endif %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('accounts.transactions', page=pagination.pages, **request.args) }}">
                            {{ pagination.pages }}
                        </a>
                    </li>
                {% endif %}

                <!-- 下一页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_next }}">
                    <a class="page-link" href="{{ url_for('accounts.transactions', page=pagination.current_page+1, **request.args) }}"
                       aria-label="下一页">
                        <i class="fas fa-angle-right"></i>
                    </a>
                </li>

                <!-- 末页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_next }}">
                    <a class="page-link" href="{{ url_for('accounts.transactions', page=pagination.pages, **request.args) }}"
                       aria-label="末页">
                        <i class="fas fa-angle-double-right"></i>
                    </a>
                </li>
            </ul>
        </nav>

        <!-- 分页信息 -->
        <div class="text-center text-muted mt-2">
            <small>
                显示第 {{ (pagination.current_page - 1) * pagination.per_page + 1 }} -
                {{ pagination.current_page * pagination.per_page if pagination.current_page * pagination.per_page < pagination.total else pagination.total }}
                条，共 {{ pagination.total }} 条记录
            </small>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 计算并显示汇总信息
    calculateSummary();

    // 表单自动提交
    $('.filter-form select, .filter-form input[type="date"]').change(function() {
        // 添加加载动画
        showLoading();
        $('#filterForm').submit();
    });

    // 每页显示数量变化时自动提交
    $('select[name="page_size"]').change(function() {
        showLoading();
        $('#filterForm').submit();
    });

    // 导出功能
    $('#exportBtn').click(function() {
        exportTransactions();
    });

    // 页面加载动画
    $('.transaction-item').each(function(index) {
        $(this).delay(index * 100).fadeIn(600);
    });
});

// 计算汇总信息
function calculateSummary() {
    let totalIncome = 0;
    let totalExpense = 0;

    $('.transaction-amount').each(function() {
        const text = $(this).text();
        const amount = parseFloat(text.replace(/[¥+,]/g, ''));

        if (!isNaN(amount)) {
            if (amount > 0) {
                totalIncome += amount;
            } else {
                totalExpense += Math.abs(amount);
            }
        }
    });

    const netAmount = totalIncome - totalExpense;

    $('#totalIncome').text('¥' + totalIncome.toFixed(2));
    $('#totalExpense').text('¥' + totalExpense.toFixed(2));
    $('#netAmount').text((netAmount >= 0 ? '+¥' : '-¥') + Math.abs(netAmount).toFixed(2));

    // 设置净额颜色
    if (netAmount > 0) {
        $('#netAmount').removeClass('text-danger').addClass('text-success');
    } else if (netAmount < 0) {
        $('#netAmount').removeClass('text-success').addClass('text-danger');
    }
}

// 显示加载动画
function showLoading() {
    $('.transaction-list').html(`
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2 text-muted">正在加载交易记录...</p>
        </div>
    `);
}

// 导出交易记录
function exportTransactions() {
    const params = new URLSearchParams();

    // 获取当前筛选条件
    const formData = new FormData(document.getElementById('filterForm'));
    for (let [key, value] of formData.entries()) {
        if (value) {
            params.append(key, value);
        }
    }

    // 添加导出标识
    params.append('export', 'true');

    // 创建下载链接
    const downloadUrl = '{{ url_for("accounts.transactions") }}?' + params.toString();

    // 创建临时下载链接
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'transactions_' + new Date().toISOString().slice(0, 10) + '.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 显示成功提示
    showAlert('交易记录导出中，请稍候...', 'info');
}

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    // 3秒后自动隐藏
    setTimeout(function() {
        $('.alert').fadeOut();
    }, 3000);
}

// 日期范围验证
$('input[name="start_date"], input[name="end_date"]').change(function() {
    const startDate = $('input[name="start_date"]').val();
    const endDate = $('input[name="end_date"]').val();

    if (startDate && endDate) {
        const start = new Date(startDate);
        const end = new Date(endDate);

        if (start > end) {
            showAlert('开始日期不能晚于结束日期', 'warning');
            $(this).val('');
            return false;
        }

        // 检查日期范围是否超过1年
        const oneYear = 365 * 24 * 60 * 60 * 1000; // 毫秒
        if (end - start > oneYear) {
            showAlert('查询范围不能超过1年', 'warning');
            $(this).val('');
            return false;
        }
    }
});

// 交易项点击效果
$('.transaction-item').click(function(e) {
    // 如果点击的是按钮，不执行跳转
    if ($(e.target).closest('.btn').length > 0) {
        return;
    }

    // 获取详情链接并跳转
    const detailLink = $(this).find('a[href*="transaction_detail"]').attr('href');
    if (detailLink) {
        window.location.href = detailLink;
    }
});

// 键盘快捷键
$(document).keydown(function(e) {
    // Ctrl + E 导出
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        $('#exportBtn').click();
    }

    // Ctrl + R 重置筛选
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        window.location.href = '{{ url_for("accounts.transactions") }}';
    }
});
</script>
{% endblock %}